﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using Web.SystemConfig.Services;
using System.ComponentModel;
using System.Web.UI.HtmlControls;
using EPlanet.Web.UI.WebControls;
using System.Data;
using DreamBuilder.UI.UserControls;
using DreamBuilder.Core.Message;
using CommonModule;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using Web.SystemLogin.Business;
using System.Threading;


namespace Web.Views.SystemConfig
{
    public partial class MenuTableEdit : PageBase
    {
        #region 控件及变量定义
        /// <summary>
        /// 工具条控件
        /// </summary>
        protected EPlanet.Web.UI.WebControls.ToolBar Toolbar1;
        /// <summary>
        /// 编辑控件
        /// </summary>
        protected UCEdit uceditAuth_Menu;
        /// <summary>
        /// Business类
        /// </summary>
        [Dependency]
        public IAuth_Menu BUSAuth_Menu
        {
            get;
            set;
        }
        #endregion

        #region PageLoad方法

        private void Page_Load(object sender, System.EventArgs e)
        {try{
            SetPageProperty();
            InitControlsCultureInfo();
            if (!IsPostBack)
            {
                ShowEdit();
            }
            CreateToolMenu(Toolbar1, ToolMenuType.TYPE_Edit);
            base.CheckEditAuthorities(base.CurrentPageState);
        }
        catch (Exception ex)
        {
            WriteErrorLog(ex.Message);
            ExceptionMsg();
        }
        }

        #region SetPageProperty
        /// <summary>
        /// 设置页面的菜单属性
        /// </summary>
        private void SetPageProperty()
        {
            this.DBHelpName = DBHelperString.Dictionary;
            base.MenuID = "ePlanet.Configuration.Auth_Menu";
            if (!IsPostBack)
            {
                if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                {
                    base.CurrentPageState = PageState.State_New;
                }
                else
                {
                    base.CurrentPageState = PageState.State_Edit;
                    base.PKValue = Request.QueryString.Get("pkValue");
                }
            }
        }
        #endregion

        /// <summary>
        /// 显示列表,为列表控件的单据id赋值
        /// </summary>
        private void ShowEdit()
        {
            uceditAuth_Menu.VoucherID = "vch_Auth_Menu";
            this.ChildAuth_Function.ChildEditID = "child_Auth_Function";
            uceditAuth_Menu.PKValue = base.PKValue;
            ChildAuth_Function.ParentKey = base.PKValue;
            this.txtMenuDesc.Text = BUSAuth_Menu.GetMenuDesc(base.PKValue);
        }

        /// <summary>
        /// 初始化控件多语信息
        /// </summary>
        private void InitControlsCultureInfo()
        {
            this.TabControl1.Items[0].Caption = GetString("Auth_MenuEdit");
        }

        #endregion

        #region OnPreRender方法

        /// <summary>
        /// 重写OnPreRender方法
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            SetParentID();
            SetEditIDEnabled();
            SetChildRefRange();
            base.OnPreRender(e);
        }

        private void SetChildRefRange()
        {
            RefButton refFunc = this.ChildAuth_Function.FindControl("RefButton1") as RefButton;
            if (refFunc != null)
            {
                refFunc.WhereSql = "P_BT_CodeTable.Code_type='Function_Name'";
                refFunc.Refresh();
            }
        }

        /// <summary>
        /// 编辑时父节点id，子节点id不可编辑
        /// </summary>
        private void SetEditIDEnabled()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["pkValue"]))
            {
                #region 父节点id
                DDLReference ddlParent = this.uceditAuth_Menu.FindControl(this.uceditAuth_Menu.GetEditControlID("P_Auth_Menu", "Parent_Menu_ID")) as DDLReference;
                if (ddlParent!=null)
                {
                    ddlParent.Enabled = false;
                }

                RefEditor refParent = this.uceditAuth_Menu.FindControl(this.uceditAuth_Menu.GetEditControlID("P_Auth_Menu", "Parent_Menu_ID")) as RefEditor;
                if (refParent != null)
                {
                    refParent.Enabled = false;
                }

                RBLReference rblParent = this.uceditAuth_Menu.FindControl(this.uceditAuth_Menu.GetEditControlID("P_Auth_Menu", "Parent_Menu_ID")) as RBLReference;
                if (rblParent != null)
                {
                    rblParent.Enable = false;
                }
                #endregion

                #region 子节点id
                TextBox txtSub = this.uceditAuth_Menu.FindControl(this.uceditAuth_Menu.GetEditControlID("P_Auth_Menu", "Submenu_ID")) as TextBox;
                if (txtSub != null)
                {
                    txtSub.Enabled = false;
                }
                #endregion
            }
        }

        #region 初始化父节点id
        private void SetParentID()
        {

            //Find找到父菜单ID
            TextBox txtParentID = this.uceditAuth_Menu.FindControl(this.uceditAuth_Menu.GetEditControlID("P_Auth_Menu", "Parent_Menu_ID")) as TextBox;
            //设置ID
            if (txtParentID != null)
            {
                if (string.IsNullOrEmpty(txtParentID.Text))
                {
                    txtParentID.Text = Request.QueryString.Get("Parent_Menu_ID").ToString();
                }
            }

        }
        #endregion

        #endregion


        #region 事件处理方法
        /// <summary>
        /// 工具条事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Toolbar1_MenuItemClick(object sender, MenuItemClickEventArgs e)
        {
           try{
               switch (e.EventItem.ID.ToString().ToLower())
            {
                case "tbsave":
                    this.Validate();
                    if (this.IsValid)
                    {
                        OnSaveData();
                    }
                    break;
                case "tbcancel":
                    RedirectList(Request.QueryString.Get("Parent_Menu_ID").ToString());
                    break;
                case "tbhelp":
                    break;
            }
        }

           catch (Exception ex)
           {
               WriteErrorLog(ex.Message);
               ExceptionMsg();
           }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存数据
        /// </summary>
        private void OnSaveData()
        {
            //构建DataSet
            System.Data.DataSet dsInfo = new System.Data.DataSet();
            //取主表，存主表
            DataTable dtMain = uceditAuth_Menu.GetEditDataTable();           
            dsInfo.Tables.Add(dtMain);
            //处理主表数据
            HandleMainTable(dsInfo.Tables[0]);
            //取子表，设置外键值，存子表
            DataTable dtChild = this.ChildAuth_Function.GetChildDataTable();
            this.ChildAuth_Function.SetFKValue(dtChild, dtMain.Rows[0]["P_Auth_Menu.Menu_ID"].ToString());
            string mainKey = dtMain.Rows[0]["P_Auth_Menu.Menu_ID"].ToString();
            HandleChildTable(dtChild);
            dsInfo.Tables.Add(dtChild);
            if (dsInfo != null)
            {
            
                ResultInfo result = BUSAuth_Menu.Save(dsInfo);
                if (result.bSuccess == true)
                {
                    if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                    {
                        BUSAuth_Menu.SaveMenuDesc(mainKey, this.txtMenuDesc.Text);
                        string operationMessage = this.CurrentUser.Real_Name + "新增了" + mainKey + "的菜单";
                        WriteUserLog(operationMessage,OracleLogType.System);
                    }
                    else
                    {
                        string operationMessage = this.CurrentUser.Real_Name + "修改了" + mainKey + "的菜单";
                        BUSAuth_Menu.SaveMenuDesc(mainKey, this.txtMenuDesc.Text);
                        WriteUserLog(operationMessage,OracleLogType.System);
                    }
                    RedirectList(Request.QueryString.Get("Parent_Menu_ID").ToString());
                }
                else
                {
                    DisplayMessage(result.ErrorDesc);
                }
            }
        }

        private void HandleChildTable(DataTable dtChild)
        {
            foreach (DataRow dr in dtChild.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    dr["P_Auth_Function.Func_Code"] = dr["P_Auth_Function.Menu_ID"].ToString() + "." + BUSAuth_Menu.GetFuncName(dr["P_Auth_Function.Func_Name_ID"].ToString());
                }
            }
        }

        /// <summary>
        /// 处理主表数据
        /// </summary>
        /// <param name="dataTable"></param>
        private void HandleMainTable(DataTable dataTable)
        {
            dataTable.Rows[0]["P_Auth_Menu.Menu_ID"] = dataTable.Rows[0]["P_Auth_Menu.Parent_Menu_ID"].ToString() + "." + dataTable.Rows[0]["P_Auth_Menu.Submenu_ID"].ToString();
        }


        #endregion

        #region 页面跳转
        /// <summary>
        /// 跳转到列表页面
        /// </summary>
        private void RedirectList(string Parent_Menu_ID)
        {
            Parent_Menu_ID = Request.QueryString.Get("Parent_Menu_ID").ToString();
            Response.Redirect("Auth_Menu.aspx?Parent_Menu_ID=" + Parent_Menu_ID);
        }
        #endregion

        #region OnInit
        override protected void OnInit(EventArgs e)
        {
            //
            //CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// 添加页面及控件事件
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            this.Toolbar1.MenuItemClick += new EPlanet.Web.UI.WebControls.MenuItemClickedEventHandler(Toolbar1_MenuItemClick);
        }

 
        #endregion

     
    }
}
